package com.woniuxy.rbac.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.woniuxy.rbac.entity.Role;
import com.woniuxy.rbac.exception.RoleNameExistException;
import com.woniuxy.rbac.mapper.RoleMapper;
import com.woniuxy.rbac.mapper.RolePermMapper;
import com.woniuxy.rbac.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 角色Service实现类
 *
 * @Auther: 老谭（<a href="http://www.woniuxy.com">蜗牛学苑</a>）
 */
@Service
public class RoleServiceImpl implements RoleService {
    @Autowired
    private RoleMapper roleMapper;

    @Autowired
    private RolePermMapper rolePermMapper;

    @Override
    @Transactional
    public void add(Role role, Integer[] permIds) {
        //判断角色名是否存在
        if (roleMapper.getNumOfName(role.getName()) == 1) {
            throw new RoleNameExistException("角色名:" + role.getName() + "已存在");
        }
        role.setStatus(Role.ENABLE);
        roleMapper.insert(role);

        for (int permId : permIds) {
            rolePermMapper.insert(role.getId(), permId);
        }

    }

    @Override
    @Transactional
    public void update(Role role, Integer[] permIds) {
//        role.setStatus("y");
        //TODO 判断角色名与其他的角色名不重复
        Role r = roleMapper.getByName(role.getName());
        if (r != null && r.getId() != role.getId()) {
            throw new RoleNameExistException("角色名重复");
        }
        //模拟潜在的数据并发修改问题
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
//        Role oldRole=roleMapper.getById(role.getId());
//        oldRole.setName(role.getName());
//        oldRole.setDescription(role.getDescription());

//        BeanUtils.copyProperties(role,oldRole);

        roleMapper.update(role);   //Java动态SQL
        rolePermMapper.delByRoleId(role.getId());
        for (int permId : permIds) {
            rolePermMapper.insert(role.getId(), permId);
        }


    }

    @Override
    public List<Role> getAll() {
        return roleMapper.getAll(null);
    }

    @Override
    public PageInfo<Role> getByCondition(int pageNum, Role role) {
        PageHelper.startPage(pageNum, 2);//开启分页
        List<Role> roles = roleMapper.getAll(role);
        return new PageInfo<>(roles);
    }

    @Transactional(readOnly = true)
    @Override
    public Role getById(int id) {
        return roleMapper.getById(id);
    }

}
